#!/bin/env python


import ConfigParser
import sys
import os
import imp
import new

class Abstract():
    def read_config(self,config_file):
        '''return value is:
            {sec_name:[(key:value),(key:value)]
            ... 
            } 
        '''
        data_dict = {}
        cf = ConfigParser.ConfigParser()
        if not os.path.exists(config_file): 
            print >>sys.stderr,"%s not exist!"%config_file
            os._exit(-1)
        cf.read(config_file)
        for sec in cf.sections():
            data_dict[sec] = {}
            for items in cf.items(sec):
                data_dict[sec][items[0]] = items[1]
        return data_dict  

    def call_instance_function(self,instance,func,**kvs):
        func = getattr(instance, func)  
        if func:
            return apply(func,(),kvs)
        return False

    def new_instance(self,module_name,subclass):
        aMod = self.module_import(module_name)
        aClass= getattr(aMod, subclass)  
        obj = new.instance(aClass)  
        #run obj's function name
        #fun = getattr(obj, "abc")  
        #apply(fun)
        return obj

    def module_import(self,name):
        '''try:
            file, pathname, description = imp.find_module(name)
            module = imp.load_module(name, file, pathname, description)
            #print file,pathname,description
        except :
            print "import", name, "fail!"
            sys.exit(-1)
        '''
        file, pathname, description = imp.find_module(name)
        module = imp.load_module(name, file, pathname, description)
        return module
